<?php
namespace App\Common;

use Uuid;
class uuidMath
{
    /**
     * 生成 uuid值 16进制
     */
    static public function createUuid(){
        return Uuid::generate(4)->hex;
    }
    
    /**
     * 将 $frombase进制的字符串， 由 $frombase进制 转换  为$tobase 进制
     * @param string $str， 待转换的字符串
     * @param number $frombase，标识原始字符串的进制
     * @param number $tobase，目标进制格式
     */
    public static function str_baseconvert($str, $frombase=10, $tobase=36) {
        $str = trim($str);
        if (intval($frombase) != 10) {
            $len = strlen($str);
            $q = 0;
            for ($i=0; $i<$len; $i++) {
                $r = base_convert($str[$i], $frombase, 10);
                $q = bcadd(bcmul($q, $frombase), $r);
            }
        }
        else $q = $str;
    
        if (intval($tobase) != 10) {
            $s = '';
            while (bccomp($q, '0', 0) > 0) {
                $r = intval(bcmod($q, $tobase));
                $s = base_convert($r, 10, $tobase) . $s;
                $q = bcdiv($q, $tobase, 0);
            }
        }
        else $s = $q;
    
        return $s;
    }
    
    /**
     * 将10进制数转换为62进制数
     * @param bigint $num 十进制整型数
     * @return 62进制字符串
     */
    public static function base10to62($num) {
        $to = 'abcBCD567defgh34xyzA89qrstuvwEFGHiMNOPQRSTnop01UVjklm2IJKLWXYZ';
        $toBase = str_split($to);
        $toLen = strlen($to);
        if ($num < strlen($to)) {
            return $toBase[$num];
        }
        $retval = '';
        while ($num != '0') {
            $retval = $toBase[bcmod($num, $toLen)] . $retval;
            $num = bcdiv($num, $toLen, 0);
        }
        return $retval;
    }
   
    /**
     * 将16进制的uuid转换为 62进制
     * @param unknown $uuidHex
     */
    static public function uuid2Base62($uuidHex){
        return self::base10to62(self::str_baseconvert($uuidHex,16,10)) ;
    }
    
    
    
}

?>